import {messages} from "share/common";
import React from 'react'
import menuRoute from 'routes/menuRoute'
import {connect} from 'react-redux'
import {Steps, Icon, Button, Row, Col, Tabs, Input, message, Spin, Popover, Modal, Form, Upload} from 'antd';
const Step = Steps.Step;
const TextArea = Input.TextArea;
const FormItem = Form.Item;
import zhifubao from "images/senior-service-open/zhifubao.png"
import verificationImg from 'images/senior-service-open/verification.png'
import 'styles/senior-service-open/order-pay.scss'
import seniorService from 'containers/increment-service/senior-service-open/senior-service.service'
import config from "config";
import configureStore from "stores";

class OrderPay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      btnLoading: false,
      payLoading: false,
      hasPayed: false,
      payWay: 'zhifubao', //支付方式: transfer 转账/汇款
      orderInfo: {},
      chargeStrategyId: undefined,
      applyInvoice: menuRoute.getRouteItem('apply-invoice'), //申请开票
      orderConfirm: menuRoute.getRouteItem('order-confirm'), //申请开票
      fileList: [],
      visible: false,
      previewVisible: false,
      src: '',//预览图片的src
    }
  }

  componentDidMount() {
    this.getInfo()
  }

  getInfo = () => {
    this.setState({loading: true});
    seniorService.getOrderDetail(this.props.params.orderId).then(res => {
      this.setState({
        loading: false,
        orderInfo: res.data,
        chargeStrategyId: res.data.chargeStrategyId,
        hasPayed: res.data.subStatus === "WAIT_CONFIRM_PAYMENT" || res.data.status === "PAID",
        payWay: res.data.status === "PAID" ? "zhifubao" : (res.data.subStatus === "WAIT_CONFIRM_PAYMENT" ? "transfer" : "zhifubao")
      })
    }).catch(err => {
      this.setState({loading: false});
    })
  };

  //复制账户信息
  copyAccountInfo = () => {
    document.getElementsByClassName('account-copy-info')[0].select();
    document.execCommand("copy");
    message.success(messages('senior-service-open.key64')/*复制成功*/)
  };

  //申请开票
  toApplyInvoice = () => {
    this.context.router.push(this.state.applyInvoice.url.replace(':orderId', this.props.params.orderId))
  };

  //点击 已付款 按钮
  handlePayed = () => {
    const {fileList} = this.state;
    if(fileList.length) {
      let params = {
        id: this.state.orderInfo.id,
        path: fileList[0].response.fileURL,
      };
      this.setState({btnLoading: true});
      seniorService.updateOrderSubStatus(params).then(res => {
        this.setState({
          btnLoading: false,
          orderInfo: res.data,
          hasPayed: true,
          visible: false,
        })
      }).catch(() => {
        this.setState({btnLoading: false})
      })
    }else{
      message.error(messages('increment-service.key7')/*请上传转账截图*/);
    }
  };

  onTabChange = (activityKey) => {
    this.setState({payWay: activityKey})
  };

  clickPayTool = (e, tool) => {
    this.setState({payWay: tool})
  };

  //支付方式为支付宝时点击立即付款
  payForNow = () => {
    const {orderInfo} = this.state;
    let params = {
      orderId: orderInfo.id,
      tenantId: orderInfo.tenantId,
      userName: this.props.user.fullName,
      createdBy: this.props.user.id,
      orderType: "CHECK_INVOICE",
      source: "WEB",
      outTradeNo: orderInfo.orderCode,
      subject: "发票查验订单",
      totalAmount: orderInfo.actualAmount,
    };
    this.setState({payLoading: true});
    /*新开一个新页面支付 */
    // const newTab = window.open();
    seniorService.payForNow(params).then(res => {
      const div = document.createElement('div');
      div.innerHTML = res.data;
      /*新开一个新页面支付 */
      // newTab.document.body.appendChild(div);
      // newTab.document.forms[0].acceptCharset='UTF-8';
      // newTab.document.forms[0].submit();
      document.body.appendChild(div);
      document.forms[0].acceptCharset = 'UTF-8';
      document.forms[0].submit();
      this.setState({
        payLoading: false,
      })
    }).catch(() => {
      this.setState({payLoading: false})
    })
  };

  confirmPayment = () => {
    this.setState({
      visible: true,
    })
  };

  onCancel = () => {
    this.setState({
      visible: false,
      fileList: [],
    })
  };

  //渲染支付方式 - 转账／汇款
  renderWayTransfer = () => {
    return (
      <div className="way-transfer">
        <div> {messages('senior-service-open.key65')/*请将订单款项汇至下述账户*/}：
          <span className="copy-transfer-info" onClick={this.copyAccountInfo}><Icon
            type="copyright"/>{messages('senior-service-open.key66')/*复制转账信息*/}</span>
        </div>
        <div className="account-img">
          <div className="bank-ch">{messages('senior-service-open.key67')/*招 商 银 行*/}</div>
          <div className="bank-en">CHINA MERCHANTS BANK</div>
          <div
            className="user-name">{messages('senior-service-open.key68')/*户名*/}：
            {messages('senior-service-open.key69')/*上海甄汇信息科技有限公司*/}
            </div>
          <div className="card-number">1219-2219-6010-802</div>
          <div
            className="open-bank">{messages('senior-service-open.key15')/*开户行*/}：
            {messages('senior-service-open.key70')/*招商银行上海张江支行*/}
            </div>
          <div className="order-number">* {messages('senior-service-open.key71')/*请务必在转账备注中注明订单编号*/}：
            <span style={{wordBreak: "break-word"}}>&nbsp;{this.state.orderInfo.orderCode}</span>
          </div>
        </div>
        <div>
          <div className="info-container">
            <div>{messages('senior-service-open.key72')/*到账时间：招行1-2天，跨行3-5天（具体到账时间以银行实际到账时间为准）*/}</div>
            <div className="service-info">
              {messages('senior-service-open.key73')/*如果您有任何疑问，请立即联系客服。*/}<br/>
              {messages('senior-service-open.key74')/*邮箱*/}：service@huilianyi.com
              <br/> {messages('senior-service-open.key16')/*电话*/}：400-829-7878
            </div>
            {/*请于<span className='retain-date'>15</span>天内完成付款，逾期订单将自动关闭。我们会尽快确认到账，为您开通服务*/}
            <div dangerouslySetInnerHTML={{__html: messages('senior-service-open.key93')}}/>
            <div className="notice-info">{messages('senior-service-open.key76')/*提示：若已完成转账付款，请点击“已付款”*/}</div>
          </div>
        </div>
        <Button type="primary" loading={this.state.btnLoading}
                onClick={this.confirmPayment}
        >{messages('increment-service.key8')/*确认已转账*/}</Button>
      </div>
    )
  };

  backToLastStep = () => {
    this.context.router.push(this.state.orderConfirm.url.replace(":id", this.state.chargeStrategyId))
  };

  //上传文件时检验文件大小
  beforeUpload= (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
    const isLt3M = file.size / 1024 / 1024 > 3;
    if(!isJpgOrPng){
      message.error(messages('increment-service.key9')/*只支持上传JPG、JPEG、PNG、BMP格式文件*/);
      return false;
    }
    if (isLt3M) {
      message.error(messages('components.key624'/*文件大小不能超过3MB*/));
    }
    return !isLt3M;
  };
  //上传文件时
  handleUploadChange = (file) => {
    const isLt3M = file.file.size / 1024 / 1024 > 3;
    const isJpgOrPng = file.file.type === 'image/jpeg' || file.file.type === 'image/png' || file.file.type === 'image/bmp';
    if (isLt3M || !isJpgOrPng) {
      return;
    }else{
      this.setState({
        fileList: file.fileList,
      })
    }
  };

  //点击图片放大预览
  handlePreview = (file) => {
    this.setState({
      previewVisible: true,
      src: file.url || file.thumbUrl
    });
  };

  //取消图片放大预览
  handleCancel = () => {
    this.setState({
      previewVisible: false
    });
  };

  render() {
    const {loading, payWay, hasPayed, orderInfo, payLoading, fileList, visible, btnLoading, src, previewVisible} = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 8},
      wrapperCol: {span: 15, offset: 1}
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">{messages('feedback.key14'/*上传图片*/)}</div>
      </div>
    );
    const upload_headers = {
      'Authorization': 'Bearer ' + configureStore.store.getState().main.authToken.access_token
    };
    return (
      <div className="order-pay">
        <Steps current={2} size="small">
          <Step title={messages('senior-service-open.key2')/*选择服务*/}/>
          <Step title={messages('senior-service-open.key3')/*确认订单*/}/>
          <Step title={messages('senior-service-open.key4')/*付款*/}/>
          <Step title={messages('senior-service-open.key5')/*申请开票*/}/>
          <Step title={messages('senior-service-open.key6')/*开通设置*/}/>
        </Steps>
        <Spin spinning={loading}>
          {hasPayed ? (
            payWay === 'zhifubao' ?
              <div className={'pay-for-success-zhifubao'}>
                <div className={'pay-for-success'}>
                  <div className={'pay-for-success-head'}>
                    <span style={{color: "rgb(91, 183, 99)", fontSize: 17}}><Icon type="check-circle"/></span>
                    <span className={'pay-for-thanks'}>{messages('senior-service-open.key77')/*感谢您的购买*/}</span>
                  </div>
                  <div className={'pay-for-success-body'}>
                    <span style={{marginRight: 50}}>{messages('senior-service-open.key78')/*订单号*/}：{orderInfo.orderCode}</span>
                    {messages('senior-service-open.key79')/*支付金额*/}：
                    <span className="price">{this.filterMoney(orderInfo.actualAmount)}</span>
                    {messages('senior-service-open.key41')/*元*/}
                  </div>
                </div>
                <div className={"pay-for-success-zhifubao-footer"}>
                  <div className="info-notice">{messages('senior-service-open.key80')/*正在核实到账信息，届时汇联易将为您开通服务！*/}</div>
                  <Button disabled={!orderInfo.applyInvoiceFlag} type={'primary'} onClick={this.toApplyInvoice}>
                    {messages('senior-service-open.key5')/*申请开票*/}
                  </Button>
                </div>
              </div>
              :
              <div className="paying-container">
                <img src={verificationImg} className="paying-img"/>
                <div> {messages('increment-service.key3')/*正在核实付款信息，付款金额具体到账时间以银行为准，到账核实后，即可申请开票和进行开通设置。*/}
                </div>
                <div style={{marginTop: 5}}> {messages('increment-service.key4')/*支付结果将以邮件形式通知您，请留意！*/}
                </div>
                <br/>
                <Button disabled={!orderInfo.applyInvoiceFlag} type={'primary'} onClick={this.toApplyInvoice}>
                  {messages('senior-service-open.key5')/*申请开票*/}
                </Button>
              </div>
          ) : (
            <div>
              <Row className="order-info">
                <Col span={10} className="order-info-col">
                  {messages('senior-service-open.key83')/*订单已经提交，请支付*/}
                  <span className="price">{this.filterMoney(orderInfo.actualAmount)}</span>
                  {messages('senior-service-open.key41')/*元*/}
                </Col>
                <Col span={6} className="order-info-col" style={{whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>
                  {messages('senior-service-open.key7')/*订单编号*/}：
                  <span className="number">
                    <Popover content={orderInfo.orderCode} placement="topLeft" overlayStyle={{maxWidth: 500}}>
                    {orderInfo.orderCode}
                  </Popover>
                  </span>
                </Col>
                <Col span={7} className="order-info-col" style={{whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>
                  {messages('senior-service-open.key60')/*服务名称*/}：
                  <Popover content={orderInfo.serviceName} placement="top" overlayStyle={{maxWidth: 500}}>
                    {orderInfo.serviceName}
                  </Popover>
                </Col>
              </Row>
              <div className={"please-choose-pay"}> {messages('senior-service-open.key84')/*请选择支付方式：*/}
              </div>
              <div>
                <div className={payWay === 'zhifubao' ? "pay-tool pay-tool-choose" : "pay-tool pay-tool-not-choose"}
                     onClick={(e) => {this.clickPayTool(e, "zhifubao")}}>
                  {
                    payWay === 'zhifubao' &&
                    <div className={"pay-tool-check"}>
                      <div className={"pay-tool-icon"}><Icon type="check" style={{fontSize: 24, color: "white"}}/></div>
                    </div>
                  }
                  <div className={"pay-tool-logo"}><img src={zhifubao} style={{height: 31, width: 89}}/></div>
                </div>
                <div className={payWay === 'transfer' ? "pay-tool pay-tool-choose" : "pay-tool pay-tool-not-choose"}
                     onClick={(e) => {this.clickPayTool(e, "transfer")}}>
                  {
                    payWay === 'transfer' &&
                    <div className={"pay-tool-check"}>
                      <div className={"pay-tool-icon"}>
                        <Icon type="check" style={{fontSize: 24, color: "white"}}/>
                      </div>
                    </div>
                  }
                  <div className={"pay-tool-logo"}>
                    <span className={'pay-tool-dollar'}>￥&nbsp;</span>
                    <span className={"pay-tool-text"}>{messages('senior-service-open.key85')/*转账/付款*/}</span>
                  </div>
                </div>
              </div>
              {
                payWay === 'zhifubao' &&
                <div>
                  <div className={"pay-tool-total"}>{messages('senior-service-open.key86')/*总计*/}
                  <span className="price">{this.filterMoney(orderInfo.actualAmount)}</span>
                    {messages('senior-service-open.key41')/*元*/}
                    {/*<Button size={'large'}*/}
                    {/*style={{marginLeft: 30}}*/}
                    {/*onClick={this.backToLastStep}>{messages('senior-service-open.key56')}</Button>*/}
                    <Button type={'primary'}
                            size={'large'}
                            loading={payLoading}
                            style={{marginLeft: 20}}
                            onClick={this.payForNow}>
                      {messages('senior-service-open.key87')/*立即付款*/}
                    </Button>
                  </div>
                </div>
              }
              {payWay === 'transfer' && this.renderWayTransfer()}
              <TextArea className="account-copy-info"
                        value={messages('senior-service-open.key94', {arg1: orderInfo.orderCode})/*户名：上海甄汇信息科技有限公司\n账号：1219 2219 6010 802\n开户行：招商银行上海张江支行\n订单编号：{arg1}*/}/>
            </div>
          )}
        </Spin>
        <Modal title={messages('increment-service.key10')/*确认转账信息*/}
               visible={visible}
               onOk={this.handlePayed}
               onCancel={this.onCancel}
               confirmLoading={btnLoading}>
          <Form>
            <FormItem {...formItemLayout} label={messages('increment-service.key11')/*转账银行*/}>
              {messages('increment-service.key12')/*招商银行*/} <span style={{marginLeft: 10}}>CHINA MERCHANTS BANK</span>
            </FormItem>
            <FormItem {...formItemLayout} label={messages('senior-service-open.key68')/*户名*/}>
              {messages('senior-service-open.key69')/*上海甄汇信息科技有限公司*/}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('increment-service.key13')/*转账账号*/}>
              1219-2219-6010-802
            </FormItem>
            <FormItem {...formItemLayout} label={messages('senior-service-open.key15')/*开户行*/}>
              {messages('senior-service-open.key70')/*招商银行上海张江支行*/}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('senior-service-open.key7')/*订单编号*/}>
              {orderInfo.orderCode}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('increment-service.key14')/*转账金额*/}>
              {this.filterMoney(orderInfo.actualAmount)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span><span style={{color: "red"}}>*</span>&nbsp;{messages('increment-service.key15')/*上传转账截图*/}</span>}>
              <Row>
              <Upload action={`${config.baseUrl}/api/upload/static/attachment`}
                      headers={upload_headers}
                      fileList={fileList}
                      accept={'image/*'}
                      listType="picture-card"
                      data={{attachmentType: 'OTHER'}}
                      onPreview={this.handlePreview}
                      beforeUpload={this.beforeUpload}
                      onChange={this.handleUploadChange}>
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
              </Row>
              <Row>{messages('increment-service.key9')/*只支持上传JPG、JPEG、PNG、BMP格式文件*/}</Row>
            </FormItem>
          </Form>
        </Modal>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="加载失败" style={{ width: '100%', marginTop: 25 }} src={src} />
        </Modal>
      </div>
    )
  }
}

OrderPay.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
  }
}


const WrappedOrderPay = Form.create()(OrderPay);
export default connect(mapStateToProps)(WrappedOrderPay)
